package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *  网关鉴权过滤器
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2、获取请求路径，判断是否是登录请求，如果是登录，直接放行
        //URI 例举：/api/v1/sensitive/list
        String path = request.getURI().getPath();
        if(path.contains("/login")){
            //如果是登录，直接放行
            return chain.filter(exchange);
        }
        //3、如果不是登录，从请求中获取token
        String token = request.getHeaders().getFirst("token");
        //4、如果token不存在，返回权限不足提示
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //5、如果token存在，校验token有效性
            Payload payload = JwtUtils.getInfoFromToken(token);
            //6、如果token有效，获取token中记录的userId，存入请求头，放行即可
            Integer userId = payload.getUserId();
            //存入请求头，放行即可
            ServerHttpRequest request1 = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(userId));
            }).build();
            exchange.mutate().request(request1);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.TOKEN_INVALID);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
